package ymr.server;

import java.io.*;
import java.net.*;

import ymr.game.Game;
import ymr.gui.MainWindow;
import ymr.gui.Starter;
import ymr.log.Logger;

public class Server extends Thread{

    static Socket clientSocket = null;
    static ServerSocket serverSocket = null;
    MainWindow mw;
    static Client clients[] = new Client[10]; // max 10 klienti     
    Logger logger = new Logger();
    
    public Server(){
    	start();
    }
    
    public void run(){
		int port = 2222;
		logger.log("server startis");
		System.out.println("Server kuulab pordil: " + port);
		
		try {
		    serverSocket = new ServerSocket(port);
		    Game game = new Game();
		    logger.log("loodi mang");
		    mw = new MainWindow();
			Starter.run(mw, 600, 800); // ===========
			
			while(true){
			    try {
					clientSocket = serverSocket.accept();
					// < selleks, et massiiv lohki ei laheks
					for(int i = 0; i < clients.length; i++){
					    if(clients[i]==null){
						    (clients[i] = new Client(mw,clientSocket,clients,game)).start();
						    logger.log("saabus uus klient");
						    System.out.println("Uus klient: " + clients[i].getName());
						    break;
						}
					}
				}catch (IOException e) {
					System.out.println("Socketi loomise avarii..");
					logger.log("Socketi loomise avarii..");
				}
			}
        }
        catch (IOException e){
        	System.out.println("Viga: " + e);
        	// siis kui port juba kasutuses on
        }
    }
	
}
